package main.java.ssm.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import ssm.pojo.Admin;
import ssm.service.AdminService;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2017/6/13.
 */
@Controller
@SessionAttributes("loginAdmin")
public class AdminController {
    @Resource
    private AdminService adminService;
/**
 * 添加一个管理员信息，首先要使用get方法请求得到register页面
 */
    @RequestMapping(value="/register",method = RequestMethod.GET)
    public String register(Model model){
        model.addAttribute(new Admin());
        return "register";
    }

    /***
     * 当我们将页面请求得到后，我们会将数据转发数据库里面
     * 使用POST方法
     */

    @RequestMapping(value="/register",method=RequestMethod.POST)
    public String register(@Validated Admin admin,HttpSession session){
        Admin admin1 =adminService.findAdminByUsername(admin.getUsername());
        if (admin1!=null){
//            throw new UserException("你的输入的用户名"+admin.getUsername()+"已存在！");
            session.setAttribute("username", admin.getUsername());
            return "addError";
        }
        adminService.insert(admin);
        return "login";
    }

    /**
     * 跳转到登录界面
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 用户登录方法
     *
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, Model model,@Validated Admin admin,HttpSession session) throws LoginException {
        System.out.println(""+11111);
        Admin u = adminService.findAdminByUsername(username);
        System.out.println(">>>>>>>>>>>>>>>>>>"+u.getPassword()+ "/"+u.getUsername());
        /*判断登录信息是否正确*/
        if ("".equals(username) || "".equals(password)){
            session.setAttribute("username", admin.getUsername());
//            throw new LoginException("你的输入不完整！");
            return "loginError";
        }
        if (u == null || !password.equals(u.getPassword())) {
            session.setAttribute("username",admin.getUsername());
//            throw new LoginException("用户名或者密码错误");
            return "loginError";
        }
        model.addAttribute("loginAdmin", u);

        return "redirect:/user/users";

    }

}
